#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Views for the Forum webapp.
#
# Created on 2008-10-28.
# $Id: views.py 41 2010-07-21 10:33:30Z guolin.mobi $
#


from afcpweb.apps.common import utils
from afcpweb.apps.common.actions import get_common_data
from afcpweb.apps.forum import resources
from afcpweb.apps.forum.config import Config
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect, HttpRequest
from django.template import Context, loader, TemplateDoesNotExist
from google.appengine.api import mail
from google.appengine.ext import db
from os.path import splitext
import datetime
import random
#from django.utils.translation import gettext_lazy as _
from django.utils.translation import ugettext as _, activate

from django.conf import settings

import logging

#from google.appengine.api import users







#---------------------------------------------------------------------------------------------------
# Home page, 404 not-found page, error page and static pages
#---------------------------------------------------------------------------------------------------

def _redirect(supage_name, name, lang, defaultName, subPage = None):
	if name is None:
		name = defaultName
	if lang is None:
		lang = defaultLanguage
	if supage_name is None:
		supage_name = ""
	else:
		supage_name = "/" + supage_name
	if not subPage is None:
		name += "/" + subPage
	return HttpResponseRedirect(supage_name + "/" + name + "/" + lang + "/")


defaultLanguage = settings.LANGUAGE_CODE
#defaultLanguage = "zh-cn"


	


def home(request, lang=None):
	"Displays the Forum home page."
	
	supage_name = "home"
	
	if lang is None:
		#return _redirect(None, None, lang, "home")
		lang = defaultLanguage
	activate(lang)
	ctxt_dict = { "supage_name": supage_name,
#	              "page_name" : "/" + name,
	              "url" : request.path,
	              "lang_code" : lang,
	    	      "banner_image" : random.choice(resources.BANNER_IMAGES)
	    	    }
	
	ctxt_dict.update(get_common_data(request))
				  
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/home.html" % (Config.APP_NAME, lang) )
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

def home_with_args(request, lang=None):
	"Displays the root page, supposed to be the home page"
	
	if lang is None:
		return _redirect(None, None, lang, "home")
	elif lang == defaultLanguage:
		return HttpResponseRedirect("/")
	else:
		return home(request, lang)
	
	
	
def visitor(request, name=None, lang=None):	
	"Displays the Forum visitor page"
	
	supage_name = "visitors"
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "program")
	activate(lang)
	
	ctxt_dict = { "supage_name": supage_name,
	              "page_name" : "/" + name,
	              "url" : request.path,
	              "lang_code"    : lang, 
	              "thispage" : "entry_" + supage_name + "_" + name
	              ,"ext" : "forum/"+lang+"/static/base-visitors.html"
	}
	
	ctxt_dict.update(get_common_data(request))
	
	if name == "workpermit" and request.method == 'POST':
		msg = sendWorkPermitComment(request)
		if msg != '':
			ctxt_dict["errmsg"] = msg
		else:
			ctxt_dict["msgok"] = True
	
	if name == "sendmail":
		return_code = sendmail(request, lang)
		if return_code != OK:
			ctxt_dict.update({"error_code" : return_code})
			name = "nosendmail"
	
	if name == "applications":
		c = Candidate.all()
		results = c.fetch(100000)
		ctxt_dict["application"] = results
				  
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name) )
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

# Class used for google datastore (list of applications done)
class Candidate(db.Model):
    lastname = db.StringProperty(required=True)
    firstname = db.StringProperty(required=True)
    email = db.StringProperty(required=True)
    application_date = db.DateProperty(required=True)
    company = db.StringProperty(required=True)
    job = db.StringProperty(required=True)

OK = 0
INVALID_MAIL = 1
MISSING_ATTACHMENT = 2
REQUIRED_FIELD = 3
INVALID_EXT = 4
TOO_LARGE_ATTACHMENT = 5
EMPTY_REQUIRED_FIELD = 6

def sendmail(request, lang):
	if not mail.is_email_valid(request.POST['email']):
		return INVALID_MAIL
	
#	if len(request.POST) != 6:
#		return REQUIRED_FIELD
	
	id = unicode(request.POST.get('id', ''))
	prenom = unicode(request.POST.get('prenom', '')).capitalize()
	nom = unicode(request.POST.get('nom', '')).upper()
	email = unicode(request.POST.get('email', ''))
	company = unicode(request.POST.get('company', ''))
	job = unicode(request.POST.get('jobname', ''))
	if (len(id) == 0 or len(prenom) == 0 or len(nom) == 0 or len(email) == 0 or (company) == 0 or len(job) == 0):
		return EMPTY_REQUIRED_FIELD
	
	addressee = resources.company_emails[id]
	
#	numberOfAttachmentsAllowed = resources.attachments.get(id, resources.defaultAttachmentsNumber)
	numberOfAttachmentsSents = len(request.FILES)
	if numberOfAttachmentsSents < addressee.minattach or numberOfAttachmentsSents > addressee.maxattach:
		return MISSING_ATTACHMENT
		
	totalSize = 0
	for f in request.FILES.values():
		path, ext = splitext(f.name)
		if ext != '.doc' and ext != '.pdf':
			return INVALID_EXT
		totalSize += f.size
	#if totalSize > 1048576: # Max 1 Mo
	# Max 0.5 Mo * nombre de pièces jointes ou 10 Mo (un peu moins pour le corps du mail)
	if totalSize > numberOfAttachmentsSents * 524288 or totalSize > 10000000:
		return TOO_LARGE_ATTACHMENT
	
	tmpl = loader.get_template("%s/%s/mail/application_subject.txt" % (Config.APP_NAME, lang) )
	mail_subject = tmpl.render(Context(get_common_data(request))) % job
	
	message = mail.EmailMessage(sender=resources.sender,
#                        subject=u"%s : Nouvelle candidature envoyée par le site de l'AFCP" % job)
                        subject=mail_subject)
	
	message.to = unicode(addressee.email)
	
	if id != 'test':
		message.cc = resources.application_cc
	
	
#	message.body = u"""
#Madame, Monsieur,
#
#Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée.
#
#Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail %s
#
#Bien à vous,
#
#L'équipe AFCP
#""" % (job, prenom, nom, email)
	
	tmpl = loader.get_template("%s/%s/mail/application.txt" % (Config.APP_NAME, lang) )

	message.body = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email)

#	message.html = u"""
#<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><br/>
#Madame, Monsieur,<br/>
#<br/>
#Une nouvelle candidature pour le poste %s a été envoyée par l'intermédiaire du site de l'AFCP, l'offre y étant publiée.<br/>
#<br/>
#Veuillez trouver ci-joint le CV et la lettre de motivation de %s %s pour cette candidature. Vous pouvez le joindre à l'adresse e-mail <a href="mailto:%s">%s</a>.<br/>
#<br/>
#Bien à vous,<br/>
#<br/>
#L'équipe AFCP<br/>
#</body></html>
#""" % (job, prenom, nom, email, email)
	
	tmpl = loader.get_template("%s/%s/mail/application.html" % (Config.APP_NAME, lang) )

	message.html = tmpl.render(Context(get_common_data(request))) % (job, prenom, nom, email, email)

			
#	message.attachments = request.FILES.items()
	#message.attachments = [(filename + u"__" + replaceForbiddenCharacters(f.name), f.read()) for filename, f in request.FILES.items()]
	message.attachments = [(f.name, f.read()) for filename, f in request.FILES.items()]
	

	message.send()
	
	
	e = Candidate(
				lastname = nom,
				firstname = prenom,
				email = email,
				application_date = datetime.datetime.now().date(),
				company = company,
				job = job
				)
	e.put()
	
	return OK

#def replaceForbiddenCharacters(s):
#	p = re.compile('(\\|\/|\:|\*|\?|\"|\<|\>|\|)')
#	return p.sub('_', s)

def sendWorkPermitComment(request):
	msg = request.POST.get('message', '')
	email = request.POST.get('email', '')
	firstname = request.POST.get('firstname', '')
	firstname = firstname[:1].upper() + firstname[1:] # Capitalize
	lastname = request.POST.get('lastname', '')
	if firstname == '':
		return u"Veuillez indiquer votre prénom."
	if lastname == '':
		return u"Veuillez indiquer votre nom."
	if email == '' and msg == '':
		return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer."
	if email == '':
		return u"Veuillez indiquer un e-mail auquel vous répondre."
	if msg == '':
		return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)"
	message = mail.EmailMessage(sender=resources.sender,
                        subject=u"Commentaire envoyé par le formulaire Permis de Travail du site du Forum")
	message.to = resources.workpermit_comments_to
	message.cc = resources.workpermit_comments_cc
	message.reply_to = email
	message.body = u"Message envoyé par le formulaire Permis de Travail, par <strong>%s %s</strong> (%s) :\n\n%s" % (firstname, lastname.upper(), email, msg)
	message.send()
	return ''


def exhibitor(request, name=None, lang=None):	
	"Display the Forum visitor page"
	
	supage_name = "exhibitors"
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "visitors")
	activate(lang)
	
	ctxt_dict = { "url" : request.path,
	              "lang_code"    : lang,	
	              "supage_name": supage_name,
	              "page_name" : "/" + name, 
	              "thispage" : "entry_" + supage_name + "_" + name
	              ,"ext" : "forum/"+lang+"/static/base-exhibitors.html"
	}
	ctxt_dict.update(get_common_data(request))
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/exhibitors/%s.html" % (Config.APP_NAME,  lang, name) )
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))
	
	
VISITORS = 0
EXHIBITORS = 1

def contactVisitors(request, name=None, lang=None):
	
#	logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%("visitors",(name is None),(lang is None)))
#	if not name is None:
#		logging.error("name:%s"%name)
#	if not lang is None:
#		logging.error("lang:%s"%lang)
		
	return contact(request, name, lang, VISITORS)
	
	
def contactExhibitors(request, name=None, lang=None):
	return contact(request, name, lang, EXHIBITORS)
	
	
def contact(request, name, lang, source):
	"Display the Forum contact page."
	
	if source == VISITORS:
		supage_name = "visitors"
	else:
		supage_name = "exhibitors"
	
#	logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None)))
#	if not name is None:
#		logging.error("name:%s"%name)
#	if not lang is None:
#		logging.error("lang:%s"%lang)
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "contact", "contact")
	activate(lang)
	
	if source == VISITORS:
		ext = "forum/"+lang+"/static/base-visitors.html"
	else:
		ext = "forum/"+lang+"/static/base-exhibitors.html"
		
	ctxt_dict = {"url" : request.path,
	             "lang_code" : lang,
	             "supage_name" : supage_name,
	             "page_name" : "/contact/" + name, 
	             "thispage" : "entry_" + supage_name + "_" + name
	              ,"ext" : ext
	}
	ctxt_dict.update(get_common_data(request))
	
	if name == "contact" and request.method == 'POST':
		msg = sendMailToAfcp(request)
		if msg != '':
			ctxt_dict["errmsg"] = msg
		else:
			ctxt_dict["msgok"] = True
					
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/contact/%s.html" % (Config.APP_NAME, lang, name));
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

def sendMailToAfcp(request):
	msg = request.POST.get('message', '')
	email = request.POST.get('email', '')
	fromArg = request.POST.get('from', '')
	if email == '' and msg == '':
		return u"Veuillez indiquer un e-mail auquel vous répondre et rédiger un message avant d'envoyer."
	if email == '':
		return u"Veuillez indiquer un e-mail auquel vous répondre."
	if msg == '':
		return u"Procédez dans l'ordre et rédigez un message avant de l'envoyer :)"
	if fromArg == '':
		return u"Emplacement du formulaire sur le site non précisé."
	message = mail.EmailMessage(sender=resources.sender,
                        subject=u"Message envoyé par le formulaire de contact du site de l'AFCP, section %s" % fromArg)
	message.to = resources.contactus_emails
	message.reply_to = email
	message.body = u"Message envoyé par le formulaire de contact, par %s :\n\n%s" % (email, msg)
	message.send()
	return ''

def inscript(request, name=None, lang=None):
	"Display the Inscription Page."
	
	supage_name = "visitors"
	
	logging.error("supage_name:%s - nameisNone:%s - langisNone:%s"%(supage_name,(name is None),(lang is None)))
	if not name is None:
		logging.error("name:%s"%name)
	if not lang is None:
		logging.error("lang:%s"%lang)
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "forum2013", "inscript")
	activate(lang)

	ctxt_dict = {"url" : request.path,
	             "lang_code" : lang,
	             "supage_name" : supage_name,
	             "subpage" : "inscript",
	             "page_name" : "/" + name, 
	             "thispage" : "entry_" + supage_name + "_inscription" #Exception pour le menu à gauche
	              ,"ext" : "forum/"+lang+"/static/base-visitors.html"
	}
	ctxt_dict.update(get_common_data(request))
					
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name));
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

def saint_gobain(request, name=None, lang=None):
	"Display the Inscription Page."
	
	supage_name = "inscript"
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "test")
	activate(lang)

	ctxt_dict = {"url" : request.path,
	             "lang_code" : lang,
	             "supage_name" : supage_name,
	             "page_name" : "/" + name, 
	             "thispage" : "entry_" + supage_name + "_" + name}
	ctxt_dict.update(get_common_data(request))
					
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/inscription/%s.html" % (Config.APP_NAME, lang, name));
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

def inscription(request, name=None, lang=None):
	"Display the Inscription Page."
	
	supage_name = "inscript"
	
	if name is None or lang is None:
		return _redirect(supage_name, name, lang, "inscription")
	activate(lang)

	ctxt_dict = {"url" : request.path,
	             "lang_code" : lang,
	             "supage_name" : supage_name,
	             "page_name" : "/" + name, 
	             "thispage" : "entry_" + supage_name + "_" + name}
	ctxt_dict.update(get_common_data(request))
					
	ctxt = Context(ctxt_dict)
	try:
		tmpl = loader.get_template("%s/%s/static/visitors/%s.html" % (Config.APP_NAME, lang, name));
	except TemplateDoesNotExist:
		return not_found(request)
	return HttpResponse(tmpl.render(ctxt))

def not_found(request):
	"Displays the 404 not-found page."
    
	ctxt_dict = { "url" : request.path, }
	ctxt_dict.update(get_common_data(request))
	ctxt = Context(ctxt_dict)
	tmpl = loader.get_template("not_found.html")
	return HttpResponseNotFound(tmpl.render(ctxt))

